<template>
  <div class="app-container">
    <el-card class="filter-container">
      <div class="filter-item">
        <el-form :inline="true" :model="filterForm" class="demo-form-inline">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              @change="handleDateChange"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="代理">
            <el-select
              v-model="filterForm.agentId"
              placeholder="全部代理"
              clearable
              filterable
              :loading="agentsLoading"
              @change="handleAgentChange"
              style="width: 220px"
            >
              <el-option label="所有代理" value=""></el-option>
              <el-option
                v-for="agent in agentOptions"
                :key="agent.id"
                :label="agent.name"
                :value="agent.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="统计周期">
            <el-select v-model="filterForm.period" placeholder="请选择">
              <el-option label="按日" value="day"></el-option>
              <el-option label="按周" value="week"></el-option>
              <el-option label="按月" value="month"></el-option>
              <el-option label="按年" value="year"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="fetchData"
              :loading="loading"
              icon="el-icon-search"
              >查询</el-button
            >
            <el-button @click="resetFilter" icon="el-icon-refresh"
              >重置</el-button
            >
            <el-button-group style="margin-left: 10px">
              <el-button
                size="small"
                @click="quickSelect('today')"
                :class="{ 'active-date-btn': isActiveDate('today') }"
                >今日</el-button
              >
              <el-button
                size="small"
                @click="quickSelect('yesterday')"
                :class="{ 'active-date-btn': isActiveDate('yesterday') }"
                >昨日</el-button
              >
              <el-button
                size="small"
                @click="quickSelect('thisWeek')"
                :class="{ 'active-date-btn': isActiveDate('thisWeek') }"
                >本周</el-button
              >
              <el-button
                size="small"
                @click="quickSelect('thisMonth')"
                :class="{ 'active-date-btn': isActiveDate('thisMonth') }"
                >本月</el-button
              >
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据概览卡片 -->
    <div class="section-title">数据概览</div>
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-card-title">总激活数</div>
          <div class="stats-card-value">
            {{ overviewData.totalActivations || 0 }}
          </div>
          <div
            class="card-compare"
            :class="overviewData.salesTrend > 0 ? 'up' : 'down'"
            v-if="overviewData.salesTrend !== null"
          >
            <i
              :class="
                overviewData.salesTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'
              "
            ></i>
            <span>{{ Math.abs(overviewData.salesTrend) }}%</span>
            <span class="compare-text">较上期</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-card-title">卡密总数</div>
          <div class="stats-card-value">{{ overviewData.totalCodes || 0 }}</div>
          <div
            class="card-compare"
            :class="overviewData.ordersTrend > 0 ? 'up' : 'down'"
            v-if="overviewData.ordersTrend !== null"
          >
            <i
              :class="
                overviewData.ordersTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'
              "
            ></i>
            <span>{{ Math.abs(overviewData.ordersTrend) }}%</span>
            <span class="compare-text">较上期</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-card-title">代理数量</div>
          <div class="stats-card-value">
            {{ overviewData.totalAgents || 0 }}
          </div>
          <div
            class="card-compare"
            :class="overviewData.agentsTrend > 0 ? 'up' : 'down'"
            v-if="overviewData.agentsTrend !== null"
          >
            <i
              :class="
                overviewData.agentsTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'
              "
            ></i>
            <span>{{ Math.abs(overviewData.agentsTrend) }}%</span>
            <span class="compare-text">较上期</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-card-title">激活转化率</div>
          <div class="stats-card-value">
            {{ overviewData.activationRate || 0 }}%
          </div>
          <div
            class="card-compare"
            :class="overviewData.conversionTrend > 0 ? 'up' : 'down'"
            v-if="overviewData.conversionTrend !== null"
          >
            <i
              :class="
                overviewData.conversionTrend > 0
                  ? 'el-icon-top'
                  : 'el-icon-bottom'
              "
            ></i>
            <span>{{ Math.abs(overviewData.conversionTrend) }}%</span>
            <span class="compare-text">较上期</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销售明细 -->
    <div class="section-title">销售明细</div>
    <el-card class="table-card">
      <template #header>
        <div class="clearfix">
          <span>代理激活明细</span>
          <el-button
            style="float: right; padding: 3px 0"
            type="text"
            @click="exportAgentDetails"
          >
            导出数据
          </el-button>
        </div>
      </template>
      <el-table
        v-loading="tableLoading"
        :data="agentDetailData"
        border
        style="width: 100%"
      >
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column
          prop="agent_name"
          label="代理名称"
          width="120"
          v-if="!filterForm.agentId"
        />
        <el-table-column prop="orderCount" label="卡密总数" width="100" />
        <el-table-column prop="activationCount" label="已激活数" width="100" />
        <el-table-column label="未激活数" width="100">
          <template #default="scope">
            {{ scope.row.orderCount - scope.row.activationCount }}
          </template>
        </el-table-column>
        <el-table-column label="激活率" width="100">
          <template #default="scope">
            {{ scope.row.conversionRate }}%
          </template>
        </el-table-column>
        <el-table-column label="佣金" width="120">
          <template #default="scope">
            {{ scope.row.commission | formatCurrency }}
          </template>
        </el-table-column>
        <el-table-column prop="userCount" label="新增用户" width="100" />
        <el-table-column label="状态分布" min-width="180">
          <template #default="scope">
            <div v-if="scope.row.statusData">
              <el-tag
                type="success"
                size="mini"
                v-if="scope.row.statusData['已售卖']"
                >已售卖: {{ scope.row.statusData["已售卖"] }}</el-tag
              >
              <el-tag
                type="info"
                size="mini"
                v-if="scope.row.statusData['未售卖']"
                style="margin-left: 5px"
                >未售卖: {{ scope.row.statusData["未售卖"] }}</el-tag
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 图表展示 -->
    <div class="section-title">销售趋势</div>
    <el-row :gutter="20" class="chart-container">
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="clearfix">
              <span>代理激活排名</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click="refreshChart('ranking')"
              >
                刷新图表
              </el-button>
            </div>
          </template>
          <div class="chart-wrapper">
            <div id="rankingChart" style="width: 100%; height: 340px"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getAgentList } from "@/api/agents";
import {
  getSystemSalesAnalysis,
  getAgentActivationDetails,
  exportSystemSalesData,
} from "@/api/statistics";
import * as echarts from "echarts";

export default {
  name: "SalesAnalysis",
  filters: {
    formatCurrency(value) {
      if (!value) return "¥0.00";
      return "¥" + Number(value).toFixed(2);
    },
  },
  data() {
    return {
      filterForm: {
        dateRange: [],
        agentId: "",
        period: "month",
      },
      agentsLoading: false,
      loading: false,
      activeDate: null,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 3);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      agentOptions: [],
      overviewData: {
        totalActivations: 0,
        totalCodes: 0,
        totalAgents: 0,
        activationRate: 0,
        salesTrend: null,
        ordersTrend: null,
        agentsTrend: null,
        conversionTrend: null,
      },
      trendType: "sales",
      trendData: {
        labels: [],
        sales: [],
        orders: [],
      },
      agentRankingData: {
        labels: [],
        sales: [],
      },
      agentDetailData: [],
      tableLoading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  watch: {
    trendType(newVal) {
      this.updateTrendChart(newVal);
    },
  },
  created() {
    this.initDateRange();
    this.fetchAgentOptions();

    // 初始化时获取所有数据
    setTimeout(() => {
      this.fetchData();
    }, 200);
  },
  mounted() {
    // 添加全局错误处理
    window.addEventListener("error", (event) => {
      console.error("全局错误:", event.error);
    });

    // 初始化两个图表
    this.$nextTick(() => {
      // 初始化趋势图表
      this.updateTrendChart(this.trendType);

      // 初始化排名图表
      this.updateRankingChart();
    });
  },
  methods: {
    initDateRange() {
      try {
        const end = new Date();
        const start = new Date();
        start.setMonth(start.getMonth() - 1);
        const endStr = this.formatDate(end);
        const startStr = this.formatDate(start);
        console.log("初始化日期范围:", startStr, endStr);
        this.filterForm.dateRange = [startStr, endStr];
      } catch (error) {
        console.error("初始化日期范围错误:", error);
        // 设置一个安全的默认值
        const today = new Date();
        const todayStr = this.formatDate(today);
        this.filterForm.dateRange = [todayStr, todayStr];
      }
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    // 日期快捷选择
    quickSelect(type) {
      const today = new Date();
      const todayStr = this.formatDate(today);

      // 设置当前活动的日期类型，用于UI高亮显示
      this.activeDate = type;

      switch (type) {
        case "today":
          this.filterForm.dateRange = [todayStr, todayStr];
          this.filterForm.period = "day";
          this.$message.info("查询今日数据");
          break;
        case "yesterday":
          const yesterday = new Date(today);
          yesterday.setDate(yesterday.getDate() - 1);
          const yesterdayStr = this.formatDate(yesterday);
          this.filterForm.dateRange = [yesterdayStr, yesterdayStr];
          this.filterForm.period = "day";
          this.$message.info("查询昨日数据");
          break;
        case "thisWeek":
          const weekStart = new Date(today);
          // 获取本周一，0是周日，1是周一
          const day = today.getDay() || 7;
          weekStart.setDate(today.getDate() - day + 1);
          this.filterForm.dateRange = [this.formatDate(weekStart), todayStr];
          this.filterForm.period = "day";
          this.$message.info("查询本周数据");
          break;
        case "thisMonth":
          const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
          this.filterForm.dateRange = [this.formatDate(monthStart), todayStr];
          this.filterForm.period = "day";
          this.$message.info("查询本月数据");
          break;
      }

      // 执行查询
      this.$nextTick(() => {
        this.fetchData();
      });
    },

    // 判断当前日期按钮是否处于活动状态
    isActiveDate(type) {
      return this.activeDate === type;
    },
    async fetchAgentOptions() {
      this.agentsLoading = true;
      try {
        const response = await getAgentList({ pageSize: 1000 });
        if (response.code === 0 && response.data) {
          this.agentOptions = response.data.items || [];
          console.log("获取到代理列表:", this.agentOptions.length, "个代理");
        }
      } catch (error) {
        console.error("获取代理列表失败", error);
        this.$message.error("获取代理列表失败");
      } finally {
        this.agentsLoading = false;
      }
    },

    handleAgentChange(value) {
      console.log("选择的代理ID:", value);
      if (value) {
        const agent = this.agentOptions.find((item) => item.id === value);
        if (agent) {
          this.$message.success(`已选择代理: ${agent.name}`);
        }
      } else {
        this.$message.info("查询所有代理");
      }
    },
    async fetchData() {
      this.loading = true;
      try {
        this.$message.info("正在加载数据...");
        console.log("查询参数:", this.filterForm);

        // 错误处理和日期校验
        if (
          this.filterForm.dateRange &&
          (!Array.isArray(this.filterForm.dateRange) ||
            this.filterForm.dateRange.length !== 2)
        ) {
          this.$message.warning("日期范围选择有误，已重置为默认值");
          this.initDateRange();
        }

        // 先获取概览数据
        await this.fetchOverviewData();

        // 再获取趋势和排名数据
        await this.fetchTrendData();
        await this.fetchRankingData();

        // 最后获取明细数据
        await this.fetchAgentDetails();

        console.log("所有数据加载完成");
        this.$message.success("数据加载完成");
      } catch (error) {
        console.error("获取数据失败", error);
        this.$message.error("获取数据失败，请重试");
      } finally {
        this.loading = false;
      }
    },
    async fetchOverviewData() {
      try {
        const params = this.getBaseParams();
        const response = await getSystemSalesAnalysis({
          ...params,
          type: "overview",
        });
        if (response.code === 0 && response.data) {
          // 处理返回的数据，确保字段名称正确
          const data = response.data;
          console.log("API返回的概览数据:", data);

          this.overviewData = {
            // 支持新旧字段名，优先使用新字段名
            totalActivations:
              data.total_activations !== undefined
                ? data.total_activations
                : data.totalSales || 0,
            totalCodes:
              data.total_codes !== undefined
                ? data.total_codes
                : data.totalOrders || 0,
            totalAgents:
              data.total_agents !== undefined
                ? data.total_agents
                : data.totalAgents || 0,
            activationRate:
              data.activation_rate !== undefined
                ? data.activation_rate
                : data.conversionRate || 0,
            salesTrend:
              data.activations_trend !== undefined
                ? data.activations_trend
                : data.salesTrend || null,
            ordersTrend:
              data.codes_trend !== undefined
                ? data.codes_trend
                : data.ordersTrend || null,
            agentsTrend:
              data.agents_trend !== undefined
                ? data.agents_trend
                : data.agentsTrend || null,
            conversionTrend:
              data.activation_rate_trend !== undefined
                ? data.activation_rate_trend
                : data.conversionTrend || null,
          };

          console.log("处理后的概览数据:", this.overviewData);
        }
      } catch (error) {
        console.error("获取激活概览数据失败", error);
        this.$message.error("获取激活概览数据失败");
      }
    },
    async fetchTrendData() {
      try {
        const params = this.getBaseParams();
        const response = await getSystemSalesAnalysis({
          ...params,
          type: "trend",
        });
        if (response.code === 0 && response.data) {
          const data = response.data;
          console.log("趋势数据:", data);
          this.trendData = data;
          this.updateTrendChart(this.trendType);
        }
      } catch (error) {
        console.error("获取激活趋势数据失败", error);
        this.$message.error("获取激活趋势数据失败");
      }
    },
    updateTrendChart(type) {
      this.$nextTick(() => {
        const chartDom = document.getElementById("trendChart");
        if (!chartDom) return;

        let chart = echarts.getInstanceByDom(chartDom);
        if (!chart) {
          chart = echarts.init(chartDom);
        }

        console.log("更新趋势图表类型:", type, "数据:", this.trendData);

        const option = {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: this.trendData.labels || [],
            axisLine: {
              lineStyle: {
                color: "#ddd",
              },
            },
            axisLabel: {
              color: "#666",
            },
          },
          yAxis: {
            type: "value",
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: "#666",
            },
            splitLine: {
              lineStyle: {
                color: "#eee",
              },
            },
          },
          series: [
            {
              name: type === "sales" ? "激活数量" : "卡密数量",
              type: "line",
              smooth: true,
              data:
                type === "sales"
                  ? this.trendData.sales || []
                  : this.trendData.orders || [],
              itemStyle: {
                color: type === "sales" ? "#409EFF" : "#67C23A",
              },
              lineStyle: {
                width: 2,
                color: type === "sales" ? "#409EFF" : "#67C23A",
              },
              areaStyle: {
                color:
                  type === "sales"
                    ? "rgba(64, 158, 255, 0.1)"
                    : "rgba(103, 194, 58, 0.1)",
              },
            },
          ],
        };

        chart.setOption(option);
      });
    },
    async fetchAgentDetails() {
      this.tableLoading = true;
      try {
        const params = {
          ...this.getBaseParams(),
          page: this.pagination.currentPage,
          page_size: this.pagination.pageSize,
        };

        // 确保agent_id参数存在，如果未指定则传空字符串表示所有代理
        if (!params.agent_id) {
          params.agent_id = "";
        }

        console.log("获取销售明细参数:", params);
        const response = await getAgentActivationDetails(params);
        console.log("获取销售明细响应:", response);

        if (response.code === 0 && response.data) {
          // 处理返回的数据
          this.agentDetailData = response.data.list || [];
          this.pagination.total = response.data.total || 0;

          // 如果返回的列表为空，显示提示信息
          if (this.agentDetailData.length === 0) {
            this.$message.info("当前查询条件下没有销售数据");
          }

          // 确保所有必要的字段都存在
          this.agentDetailData = this.agentDetailData.map((item) => ({
            ...item,
            // 确保所有必要的字段都存在，兼容snake_case和camelCase
            date: item.date || "",
            agent_name: item.agent_name || item.agentName || "未知代理",
            orderCount: item.orderCount || item.order_count || 0,
            activationCount: item.activationCount || item.activation_count || 0,
            conversionRate: item.conversionRate || item.conversion_rate || 0,
            commission: item.commission || 0,
            userCount: item.userCount || item.user_count || 0,
            statusData: item.statusData || item.status_data || {},
          }));

          console.log("处理后的销售明细数据:", this.agentDetailData);
        } else {
          this.$message.error(response.message || "获取代理激活明细失败");
        }
      } catch (error) {
        console.error("获取代理激活明细失败", error);
        this.$message.error("获取代理激活明细失败");
      } finally {
        this.tableLoading = false;
      }
    },
    getBaseParams() {
      const params = {
        period: this.filterForm.period,
      };

      // 确保正确传递代理ID参数
      if (this.filterForm.agentId) {
        params.agent_id = this.filterForm.agentId;
        console.log("查询特定代理:", this.filterForm.agentId);
      } else {
        // 明确设置为空字符串，表示查询所有代理
        params.agent_id = "";
        console.log("查询所有代理");
      }

      // 修正日期参数处理逻辑
      if (
        this.filterForm.dateRange &&
        Array.isArray(this.filterForm.dateRange) &&
        this.filterForm.dateRange.length === 2
      ) {
        // 确保日期格式正确
        try {
          params.start_date = this.filterForm.dateRange[0];
          params.end_date = this.filterForm.dateRange[1];

          // 打印日期参数，便于调试
          console.log("日期参数:", params.start_date, params.end_date);
        } catch (error) {
          console.error("日期参数处理错误:", error);
          this.$message.warning("日期格式有误，请重新选择");
        }
      } else {
        // 如果日期范围无效，设置默认值
        console.warn("日期范围无效或为空:", this.filterForm.dateRange);
        this.initDateRange();
        params.start_date = this.filterForm.dateRange[0];
        params.end_date = this.filterForm.dateRange[1];
      }

      console.log("最终请求参数:", params);
      return params;
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.fetchAgentDetails();
    },
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.fetchAgentDetails();
    },
    resetFilter() {
      this.initDateRange();
      this.filterForm.agentId = "";
      this.filterForm.period = "month";
      this.fetchData();
    },
    // 处理日期变更事件
    handleDateChange(val) {
      console.log("日期选择变更:", val);
      if (!val || val.length !== 2) {
        // 如果清空日期，重置为默认值
        this.$message.warning("请选择完整的日期范围");
        this.initDateRange();
      }
    },
    async exportAgentDetails() {
      try {
        const params = this.getBaseParams();
        const response = await exportSystemSalesData(params);

        if (
          response.type === "application/vnd.ms-excel" ||
          response.type === "application/octet-stream"
        ) {
          // 创建下载链接
          const url = window.URL.createObjectURL(
            new Blob([response], { type: response.type })
          );
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute(
            "download",
            `系统销售数据_${new Date().getTime()}.xlsx`
          );
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        } else {
          // 如果返回的不是文件，可能是错误信息
          return Promise.reject(new Error("导出失败"));
        }
      } catch (error) {
        console.error("导出数据失败", error);
        this.$message.error("导出数据失败");
      }
    },
    refreshChart(type) {
      if (type === "trend") {
        this.fetchTrendData();
      } else if (type === "ranking") {
        this.fetchRankingData();
      }
    },
    updateRankingChart() {
      this.$nextTick(() => {
        const chartDom = document.getElementById("rankingChart");
        if (!chartDom) return;

        let chart = echarts.getInstanceByDom(chartDom);
        if (!chart) {
          chart = echarts.init(chartDom);
        }

        const option = {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: {
            type: "category",
            data:
              this.agentRankingData.labels.length > 0
                ? this.agentRankingData.labels
                : ["加载中..."],
            axisLabel: {
              interval: 0,
              rotate: 45,
              formatter: function (value) {
                if (value.length > 8) {
                  return value.substring(0, 8) + "...";
                }
                return value;
              },
            },
          },
          yAxis: {
            type: "value",
          },
          series: [
            {
              name: "激活数量",
              type: "bar",
              barWidth: "60%",
              data:
                this.agentRankingData.sales.length > 0
                  ? this.agentRankingData.sales
                  : [0],
              itemStyle: {
                color: "#67C23A",
              },
              label: {
                show: true,
                position: "top",
                formatter: "{c}",
              },
            },
          ],
        };

        chart.setOption(option);
      });
    },
    async fetchRankingData() {
      try {
        const params = this.getBaseParams();
        const response = await getSystemSalesAnalysis({
          ...params,
          type: "ranking",
          limit: 10,
        });
        if (response.code === 0 && response.data) {
          const rankingData = response.data;
          console.log("排名数据:", rankingData);
          this.agentRankingData.labels = rankingData.agents || [];
          this.agentRankingData.sales = rankingData.sales || [];

          // 更新排名图表
          this.updateRankingChart();
        }
      } catch (error) {
        console.error("获取代理排名数据失败", error);
        this.$message.error("获取代理排名数据失败");
      }
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  margin-bottom: 20px;
}
.filter-item {
  margin-bottom: 10px;
}
.data-overview {
  margin-bottom: 20px;
}
.card-item {
  display: flex;
  align-items: center;
}
.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}
.card-icon svg {
  font-size: 24px;
  color: #fff;
}
.blue {
  background-color: #409eff;
}
.green {
  background-color: #67c23a;
}
.orange {
  background-color: #e6a23c;
}
.purple {
  background-color: #8e44ad;
}
.card-info {
  flex: 1;
}
.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}
.card-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}
.card-compare {
  font-size: 12px;
}
.card-compare.up {
  color: #67c23a;
}
.card-compare.down {
  color: #f56c6c;
}
.compare-text {
  color: #909399;
}
.chart-container {
  margin-bottom: 20px;
}
.chart-card {
  margin-bottom: 20px;
}
.chart-wrapper {
  position: relative;
  width: 100%;
  height: 340px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination-container {
  padding: 15px 0;
  text-align: right;
}
.section-title {
  font-size: 18px;
  font-weight: 500;
  margin: 30px 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}
.stats-cards {
  margin-bottom: 20px;
}
.stats-card {
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.stats-card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}
.stats-card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

/* 添加日期快捷按钮样式 */
.active-date-btn {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

/* 提升表单项间距 */
.el-form-item {
  margin-right: 15px;
}
</style>
